package cn.lizemin.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;

/**
 * @author lzm
 * @Date 2024/7/27
 * @description 注意事项：每个servlet有自己独立的servlet配置，彼此之间互不影响
 * 这个servletConfig是Tomcat解析web.xml后，自动调用每个servlet的init(ServletConfig config)方法传进来的
 * 类似于spring的aware接口
 */
@WebServlet(urlPatterns = "/servlet5")
public class MyServlet5 extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println(username + ":" + password);

        String[] hobbies = req.getParameterValues("hobby");
        System.out.println(Arrays.toString(hobbies));

        // 获取所有参数, springMVC做的事情不过是对入参封装为我们定义的实体类而已
        Map<String, String[]> parameterMap = req.getParameterMap();
        parameterMap.forEach((key, val) -> System.out.println(key + " = " + Arrays.toString(val)));

        System.out.println("===============getParameterNames================");
        Enumeration<String> pNames = req.getParameterNames();
        while (pNames.hasMoreElements()) {
            String pName = pNames.nextElement();
            String[] pValues = req.getParameterValues(pName);
            System.out.println(pName + " = " + Arrays.toString(pValues));
        }

        // 读取请求体中的json字符串
        System.out.println("==============read json body===================");
        BufferedReader reader = req.getReader();
        String line;
        StringBuilder jsonStr = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            jsonStr.append(line);
        }
        System.out.println(jsonStr);

    }


}
